#include "Thread.h"
#include <stdio.h>
#include <cstring>

Thread::Thread(ThreadCallback &&cb)
    : _pthid(0), _isRunning(false), _cb(std::move(cb))
{
}
void Thread::start()
{
    if (!_isRunning)
    {
        int ret = pthread_create(&_pthid, NULL, start_routine, this);
        if (ret != 0)
        {
            fprintf(stderr, "%s", strerror(ret));
            return;
        }
        _isRunning = true;
    }
}
void Thread::join()
{
    if (_isRunning)
    {
        pthread_join(_pthid, nullptr);
        _isRunning = false;
    }
}
void *Thread::start_routine(void *arg)
{
    Thread *thread = static_cast<Thread *>(arg);
    if (thread)
    {
        thread->_cb();
    }
    return nullptr;
}